package com.leyou.goods.service;

import com.leyou.goods.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;


/**
 * @author CHERRY
 * @date 2018-09-13-10:55
 */
@Service
public class GoodsHtmlService {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private GoodsService goodsService;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    /**
     * 创建html页面
     *
     * @param spuId
     */
    public void createHtml(Long spuId) {

        PrintWriter writer = null;
        try {

            Map<String, Object> map = this.goodsService.loadItemModel(spuId);

            //创建上下文对象
            Context context = new Context();

            //将页面数据放入上下文对象中
            context.setVariables(map);

            //创建输出流
            File file = new File("F:\\project\\" + spuId + ".html");
            writer = new PrintWriter(file);

            //执行页面静态化方法
            templateEngine.process("item", context, writer);

        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{}" + e, spuId);
        } finally {
            if (writer != null) {
                writer = null;
                writer.close();
            }
        }
    }

    public void asyncExecute(Long spuId) {

        ThreadUtils.excute(() -> createHtml(spuId));
        /*ThreadUtils.excute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }

}
